package org.hanyx.server;

import io.grpc.stub.StreamObserver;
import org.hanyx.grpc.hello.api.HelloRequest;
import org.hanyx.grpc.hello.api.HelloResponse;
import org.hanyx.grpc.hello.api.HelloServiceGrpc;

/**
 * HelloServiceImpl class
 *
 * @author hanyx
 * @date 2018/04/20
 */
public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {

    /**
     *
     * @param request 包含请求参数
     * @param responseObserver 通过此对象完成相应过程
     */
    @Override
    public void say(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        HelloResponse response = null;
        try {
            // 构建相应对象
            response = HelloResponse
                    .newBuilder()
                    .setMessage("hello " + request.getName())
                    .build();
        } catch (Exception e) {
            // 捕捉异常
            responseObserver.onError(e);
        } finally {
            // 把相应对象添加到 StreamObserver<HelloResponse>中
            responseObserver.onNext(response);
        }
        // 结束整个响应
        responseObserver.onCompleted();
    }
}
